package com.winbomb.kingcard.base;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import com.winbomb.kingcard.ICard;
import com.winbomb.kingcard.ICardPile;
import com.winbomb.kingcard.NoMoreCardException;
import com.winbomb.kingcard.Suit;

public class CardPile implements ICardPile {

	/** 牌的副数，即有几副牌 */
	private int deckNum = 2;

	/** 抽牌堆 */
	private List<ICard> drawPile = new ArrayList<ICard>(128);

	/** 弃牌堆 */
	private List<ICard> discardPile = new ArrayList<ICard>(128);

	public CardPile(int deckNum) {
		this.deckNum = deckNum;
	}

	@Override
	public synchronized ICard drawCard() throws NoMoreCardException {

		ICard card = getTopCard();
		drawPile.remove(0);

		return card;
	}

	@Override
	public void initPile() {

		drawPile.clear();
		discardPile.clear();

		for (int j = 0; j < deckNum; j++) {

			// 完成一副牌的初始化
			for (int i = 1; i <= 13; i++) {
				final Card cardBlk = new Card(i, Suit.SPADE);
				final Card cardHrt = new Card(i, Suit.HEART);
				final Card cardClb = new Card(i, Suit.CLUB);
				final Card cardDmd = new Card(i, Suit.DIAMOND);

				drawPile.add(cardBlk);
				drawPile.add(cardHrt);
				drawPile.add(cardClb);
				drawPile.add(cardDmd);
			}

			final Card cardBlkJk = new Card(14, Suit.BLACK);
			final Card cardRedJk = new Card(15, Suit.RED);

			drawPile.add(cardBlkJk);
			drawPile.add(cardRedJk);
		}

		// 将牌打乱顺序
		shuffle();
	}

	@Override
	public synchronized void shuffle() {

		if (discardPile != null && !discardPile.isEmpty()) {
			for (ICard card : discardPile) {
				drawPile.add(card);
			}
			discardPile.clear();
		}
		Collections.shuffle(drawPile);
	}

	@Override
	public int getTotalCardCount() {
		return drawPile.size() + discardPile.size();
	}

	@Override
	public int getDrawCardCount() {
		return drawPile.size();
	}

	@Override
	public ICard[] getDrawCards() {
		return drawPile.toArray(new ICard[drawPile.size()]);
	}

	@Override
	public int getDiscardCardCount() {
		return discardPile.size();
	}

	@Override
	public ICard[] getDiscardCards() {
		return discardPile.toArray(new ICard[discardPile.size()]);
	}

	@Override
	public void takeBack(ICard card) {
		if (card != null) {
			card.setCovered(false);
			card.setSelected(false);
			card.clearAllFlags();

			discardPile.add(card);
		}
	}

	@Override
	public void takeBack(ICard[] cards) {
		for (ICard card : cards) {
			takeBack(card);
		}
	}

	@Override
	public void takeBack(List<ICard> cards) {
		for (ICard card : cards) {
			takeBack(card);
		}
	}

	@Override
	public ICard getTopCard() throws NoMoreCardException {

		if (drawPile == null || drawPile.size() == 0) {
			shuffle();
			if (drawPile.size() == 0) {
				throw new NoMoreCardException();
			}
		}

		return drawPile.get(0);
	}

}
